package com.hailiao.beidou.message.data.store

import com.d10ng.common.transform.json
import com.hailiao.beidou.message.bd.constant.ProtoVersion
import com.hailiao.beidou.message.bd.sp.SPMode
import com.hailiao.beidou.message.data.store.contant.CommunicationMode
import com.hailiao.beidou.message.data.store.data.SPSettingData
import com.tencent.mmkv.MMKV

/**
 * 本地数据存储
 * @Author d10ng
 * @Date 2024/3/4 16:23
 */
private val mmkv by lazy {
    MMKV.defaultMMKV(MMKV.MULTI_PROCESS_MODE, null)
}

/** 设置 协议版本 */
private const val SPF_SETTING_PROTO_VERSION = "SPF_SETTING_PROTO_VERSION"
fun getSpfProtoVersion() =
    ProtoVersion.parse(mmkv.decodeDouble(SPF_SETTING_PROTO_VERSION, ProtoVersion.BD3.id))

fun setSpfProtoVersion(value: ProtoVersion) {
    mmkv.encode(SPF_SETTING_PROTO_VERSION, value.id)
}

/** 通讯模式 */
private const val COMMUNICATION_MODE = "communication_mode"
fun getSpfCommMode(): CommunicationMode =
    CommunicationMode.parse(mmkv.decodeInt(COMMUNICATION_MODE, CommunicationMode.BLE.value))

fun setSpfCommMode(mode: CommunicationMode) {
    mmkv.encode(COMMUNICATION_MODE, mode.value)
}

/** 串口通信 类型 */
private const val SPF_SETTING_SERIAL_PORT_MODE = "SPF_SETTING_SERIAL_PORT_MODE"
fun getSpSPMode() = SPMode.parse(mmkv.decodeString(SPF_SETTING_SERIAL_PORT_MODE))
fun setSpfSPMode(value: SPMode) { mmkv.encode(SPF_SETTING_SERIAL_PORT_MODE, value.text) }

/** 串口通信 配置信息 */
private const val SPF_SERIAL_PORT_SETTING_INFO = "SPF_SERIAL_PORT_SETTING_INFO"
fun getSpfSPSetting() = json.decodeFromString<SPSettingData>(
    mmkv.decodeString(
        SPF_SERIAL_PORT_SETTING_INFO,
        null
    ) ?: json.encodeToString(SPSettingData.serializer(), SPSettingData())
)

fun setSpfSPSetting(value: SPSettingData) {
    mmkv.encode(
        SPF_SERIAL_PORT_SETTING_INFO,
        json.encodeToString(SPSettingData.serializer(), value)
    )
}